using System.Runtime.CompilerServices;
using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using System.Windows.Forms;
using WinformDevFramework.Core;
using WinformDevFramework.IRepository.UnitOfWork;
using WinformDevFramework.IServices.System;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;

namespace WinformDevFramework
{
    public partial class Frmw_Buy : BaseForm1
    {
        private Iw_BuyServices _w_BuyServices;
        private IW_GoodsServices _w_GoodsServices;
        private Iw_SupplierServices _w_SupplierServices;
        private ISysUserServices _w_SysUserServices;
        private Iw_BuyDetailServices _w_BuyDetailServices;
        private Iw_SettlementAccountServices _w_SettlementAccountServices;
        private Iw_Warehouseervices _w_Warehouseervices;
        private Iw_BuyReturnServices _w_BuyReturnServices;
        private Iw_BuyInWarehouseServices _w_BuyInWarehouseServices;
        private Iw_PaymentDetailServices _w_PaymentDetailServices;
        public Frmw_Buy(Iw_BuyServices w_BuyServices, IW_GoodsServices w_GoodsServices, Iw_SupplierServices w_SupplierServices, ISysUserServices sysUserServices, Iw_BuyDetailServices w_BuyDetailServices, Iw_SettlementAccountServices w_SettlementAccountServices, Iw_Warehouseervices w_Warehouseervices, Iw_BuyReturnServices w_BuyReturnServices, Iw_BuyInWarehouseServices w_BuyInWarehouseServices, Iw_PaymentDetailServices w_PaymentDetailServices)
        {
            _w_BuyServices = w_BuyServices;
            InitializeComponent();
            _w_GoodsServices = w_GoodsServices;
            _w_SupplierServices = w_SupplierServices;
            _w_SysUserServices = sysUserServices;
            _w_BuyDetailServices = w_BuyDetailServices;
            _w_SettlementAccountServices = w_SettlementAccountServices;
            _w_Warehouseervices = w_Warehouseervices;
            _w_BuyReturnServices = w_BuyReturnServices;
            _w_BuyInWarehouseServices = w_BuyInWarehouseServices;
            _w_PaymentDetailServices = w_PaymentDetailServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();
            // 设置隐藏列
            this.dataGridViewList.Columns["BuyCode"].HeaderText = "采购单号";
            this.dataGridViewList.Columns["SupplierName"].HeaderText = "供应商";
            this.dataGridViewList.Columns["SupplierCode"].Visible = false;
            this.dataGridViewList.Columns["InvoicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["MakeUserName"].HeaderText = "制单人";
            this.dataGridViewList.Columns["DeliveryDate"].HeaderText = "交货日期";
            this.dataGridViewList.Columns["InvoicesImage"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["SettlementAccount"].Visible = false;
            this.dataGridViewList.Columns["Status"].HeaderText = "单据状态";
            this.dataGridViewList.Columns["TotalPrice"].HeaderText = "单据金额";
            this.dataGridViewList.Columns["TotalPrice1"].HeaderText = "已结金额";
            this.dataGridViewList.Columns["TotalPrice2"].HeaderText = "未结金额";
            this.GoodsName.DataSource = _w_GoodsServices.Query();
            this.GoodsName.DisplayMember = "GoodsName";
            this.GoodsName.ValueMember = "GoodsCode";

            //Warehouse.DataSource = _w_Warehouseervices.Query();
            //Warehouse.DisplayMember = "WarehouseName";
            //Warehouse.ValueMember = "ID";

            SupplierName.DataSource = _w_SupplierServices.Query();
            SupplierName.ValueMember = "SupplierCode";
            SupplierName.DisplayMember = "SupplierName";

            SettlementAccount.DataSource = _w_SettlementAccountServices.Query();
            SettlementAccount.ValueMember = "Code";
            SettlementAccount.DisplayMember = "Name";

            MakeUser.DataSource = _w_SysUserServices.Query();//值查找销售部门
            MakeUser.ValueMember = "ID";
            MakeUser.DisplayMember = "Fullname";

            //ReadOnlyControlList.Add("BuyCode");
            ReadOnlyControlList.Add("MakeUser");

            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Buy;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.BuyCode.Text = model.BuyCode.ToString();
            this.SupplierName.SelectedValue = model.SupplierCode;
            this.InvoicesDate.Text = model.InvoicesDate.ToString();
            this.MakeUser.Text = model.MakeUserName.ToString();
            this.DeliveryDate.Text = model.DeliveryDate.ToString();
            this.InvoicesImage.Tag = model.InvoicesImage.ToString();
            this.InvoicesImage.Image = model.InvoicesImage.Base64ToImage();
            this.Remark.Text = model.Remark.ToString();
            this.TotalPayable.Text = model.TotalPrice?.ToString();
            this.yijie.Text = model.TotalPrice1?.ToString();
            this.weijie.Text = model.TotalPrice2?.ToString();
            SettlementAccount.SelectedValue = model.SettlementAccount;
            //给明细表设置数据
            SetDataToDetail(GetDetailData(model.ID));
            //设置界面统计数据
            SetFormTotalData();
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            MakeUser.Enabled = false;
            MakeUser.SelectedValue = AppInfo.User.ID;
            InvoicesImage.Tag = string.Empty;
            InvoicesImage.Image = null;
            dataGridViewBuyDetail.Rows.Clear();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            if (CheckData(BuyCode.Text))
            {
                base.EditFunction(sender, e);
                SetToolButtonStatus(formStatus);
                dataGridViewBuyDetail.ReadOnly = false;
                string[] cols = { "GoodsName", "BuyNumber", "UnitPrice", "DiscountPrice", "TaxRate", "RemarkD" };
                foreach (DataGridViewColumn column in dataGridViewBuyDetail.Columns)
                {
                    if (!cols.Contains(column.Name))
                    {
                        column.ReadOnly = true;
                    }
                }
            }
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    {
                        #region 主表数据
                        bool result = false;
                        w_Buy model = new w_Buy();
                        // TODO获取界面的数据
                        if (string.IsNullOrEmpty(this.BuyCode.Text))
                        {
                            model.BuyCode = $"CG{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                        }
                        else
                        {
                            model.BuyCode = this.BuyCode.Text;
                        }
                        model.SupplierName = this.SupplierName.Text;
                        model.SupplierCode = SupplierName.SelectedValue.ToString();
                        model.InvoicesDate = this.InvoicesDate.Value;
                        model.MakeUserName = this.MakeUser.Text;
                        model.DeliveryDate = this.DeliveryDate.Value;
                        model.InvoicesImage = this.InvoicesImage.Tag.ToString();
                        model.TotalPrice = this.TotalPayable.Text.ToDecimal();
                        model.TotalPrice1 = 0;
                        model.TotalPrice2 = model.TotalPrice;
                        model.Remark = this.Remark.Text;
                        model.SettlementAccount = this.SettlementAccount.SelectedValue.ToString();
                        if (_w_BuyServices.Exists(p => p.BuyCode.Equals(model.BuyCode)))
                        {
                            MessageBox.Show("购货单号已存在！请稍后在保存！", "提示");
                            return;
                        }

                        #endregion

                        #region 明细表

                        List<w_BuyDetail> dataDetails = new List<w_BuyDetail>();
                        foreach (DataGridViewRow row in dataGridViewBuyDetail.Rows)
                        {
                            if (!row.IsNewRow)
                            {
                                w_BuyDetail detail = new w_BuyDetail();
                                detail.BuyNumber = row.Cells["BuyNumber"].FormattedValue.ToDecimal();
                                detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                                //detail.Warehouse = row.Cells["Warehouse"].Value.ToInt32();
                                detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                                detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                                detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                                detail.UnitPrice = row.Cells["UnitPrice"].FormattedValue.ToDecimal();
                                detail.DiscountPrice = row.Cells["DiscountPrice"].FormattedValue.ToDecimal();
                                detail.TotalPrice = row.Cells["TotalPriceD"].FormattedValue.ToDecimal();
                                detail.TaxRate = row.Cells["TaxRate"].FormattedValue.ToDecimal();
                                detail.TaxUnitPrice = row.Cells["TaxUnitPrice"].FormattedValue.ToDecimal();
                                detail.TaxPrice = row.Cells["TaxPrice"].FormattedValue.ToDecimal();
                                detail.TotalTaxPrice = row.Cells["TotalTaxPrice"].FormattedValue.ToDecimal();
                                detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                                dataDetails.Add(detail);
                            }
                        }

                        int id = _w_BuyServices.AddBuyInfo(model, dataDetails);
                        if (id > 0)
                        {
                            MessageBox.Show("保存成功！", "提示");
                            txtID.Text = id.ToString();
                            BuyCode.Text = model.BuyCode;
                            SetDataToDetail(GetDetailData(id));
                        }
                        #endregion
                    }

                }
                // 修改
                else
                {
                    w_Buy model = _w_BuyServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.BuyCode = this.BuyCode.Text;
                    model.SupplierName = this.SupplierName.Text;
                    model.SupplierCode = SupplierName.SelectedValue.ToString();
                    model.InvoicesDate = this.InvoicesDate.Value;
                    model.MakeUserName = this.MakeUser.Text;
                    model.DeliveryDate = this.DeliveryDate.Value;
                    model.InvoicesImage = this.InvoicesImage.Tag.ToString();
                    model.TotalPrice = this.TotalPayable.Text.ToDecimal();
                    model.Remark = this.Remark.Text;
                    model.SettlementAccount = this.SettlementAccount.SelectedValue.ToString();
                    #region 明细表

                    List<w_BuyDetail> dataDetails = new List<w_BuyDetail>();
                    foreach (DataGridViewRow row in dataGridViewBuyDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_BuyDetail detail = new w_BuyDetail();
                            detail.BuyCode = row.Cells["BuyCodeD"].FormattedValue.ToString();
                            detail.BuyID = row.Cells["BuyID"].FormattedValue.ToInt32();
                            detail.BuyDetailCode = row.Cells["BuyDetailCode"].FormattedValue.ToString();

                            detail.BuyNumber = row.Cells["BuyNumber"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString(); detail.UnitPrice = row.Cells["UnitPrice"].FormattedValue.ToDecimal();
                            detail.DiscountPrice = row.Cells["DiscountPrice"].FormattedValue.ToDecimal();
                            detail.TotalPrice = row.Cells["TotalPriceD"].FormattedValue.ToDecimal();
                            detail.TaxRate = row.Cells["TaxRate"].FormattedValue.ToDecimal();
                            detail.TaxUnitPrice = row.Cells["TaxUnitPrice"].FormattedValue.ToDecimal();
                            detail.TaxPrice = row.Cells["TaxPrice"].FormattedValue.ToDecimal();
                            detail.TotalTaxPrice = row.Cells["TotalTaxPrice"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    if (_w_BuyServices.UpdateBuyInfo(model, dataDetails))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.ID));
                    }
                    #endregion
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(txtID.Text.ToInt32()));
            SetFormTotalData();
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            if (CheckData(BuyCode.Text))
            {
                base.DelFunction(sender, e);
                var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    if (_w_BuyServices.DeleteBuyInfo(new w_Buy() { ID = txtID.Text.ToInt32() }))
                    {
                        formStatus = FormStatus.Del;
                        SetToolButtonStatus(formStatus);
                        //列表重新赋值
                        this.dataGridViewList.DataSource = GetData();
                        dataGridViewBuyDetail.Rows.Clear();
                        InvoicesImage.Tag = string.Empty;
                        InvoicesImage.Image = null;
                        //SetDataToDetail(GetDetailData());
                    }

                }
            }

        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        contextMenuStrip1.Enabled = true;
                        dataGridViewBuyDetail.ReadOnly = false;
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        contextMenuStrip1.Enabled = true;
                        dataGridViewBuyDetail.ReadOnly = false;
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        contextMenuStrip1.Enabled = false;
                        dataGridViewBuyDetail.ReadOnly = true;
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        contextMenuStrip1.Enabled = false;
                        dataGridViewBuyDetail.ReadOnly = true;
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        contextMenuStrip1.Enabled = false;
                        dataGridViewBuyDetail.ReadOnly = true;
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        contextMenuStrip1.Enabled = false;
                        dataGridViewBuyDetail.ReadOnly = true;
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        contextMenuStrip1.Enabled = false;
                        dataGridViewBuyDetail.ReadOnly = true;
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            //if (string.IsNullOrEmpty(BuyCode.Text))
            //{
            //    MessageBox.Show("请填写购货单号");
            //    BuyCode.Focus();
            //    return false;
            //}
            if (string.IsNullOrEmpty(SupplierName.Text))
            {
                MessageBox.Show("请选择供应商");
                SupplierName.Focus();
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_Buy> GetData()
        {
            List<w_Buy> data = new List<w_Buy>();
            data = _w_BuyServices.Query();
            return data;
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_BuyDetail> GetDetailData(int id)
        {
            List<w_BuyDetail> data = new List<w_BuyDetail>();
            data = _w_BuyDetailServices.QueryListByClause(p => p.BuyID == id);
            return data;
        }

        /// <summary>
        /// 明细表 设置数据
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_BuyDetail> details)
        {
            dataGridViewBuyDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewBuyDetail.Rows.AddCopy(dataGridViewBuyDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewBuyDetail.Rows[dataGridViewBuyDetail.Rows.Count - 2];
                row.Cells["BuyNumber"].Value = p.BuyNumber;
                row.Cells["GoodsName"].Value = p.GoodsCode;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                //row.Cells["Warehouse"].Value = p.Warehouse;
                row.Cells["UnitPrice"].Value = p.UnitPrice;
                row.Cells["DiscountPrice"].Value = p.DiscountPrice;
                row.Cells["TotalPriceD"].Value = p.TotalPrice;
                row.Cells["TaxRate"].Value = p.TaxRate;
                row.Cells["TaxUnitPrice"].Value = p.TaxUnitPrice;
                row.Cells["TaxPrice"].Value = p.TaxPrice;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["BuyID"].Value = p.BuyID;
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["BuyDetailCode"].Value = p.BuyDetailCode;
            });
        }
        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void SupplierName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void InvoicesImage_DoubleClick(object sender, EventArgs e)
        {
            if (InvoicesImage.Image == null) return;
            // 获取PictureBox控件中的图片
            byte[] imageBytes = Convert.FromBase64String(InvoicesImage.Tag.ToString());
            // 保存图片到临时文件
            string tempFilePath = Application.StartupPath + $"goods.{InvoicesImage.Image.RawFormat}";
            File.WriteAllBytes(tempFilePath, imageBytes);
            //建立新的系统进程    
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            //设置图片的真实路径和文件名    
            process.StartInfo.FileName = tempFilePath;

            //设置进程运行参数，这里以最大化窗口方法显示图片。    
            process.StartInfo.Arguments = "rundl132.exe C://WINDOWS//system32//shimgvw.dll,ImageView_Fullscreen";

            //此项为是否使用Shell执行程序，因系统默认为true，此项也可不设，但若设置必须为true    
            process.StartInfo.UseShellExecute = true;

            //此处可以更改进程所打开窗体的显示样式，可以不设    
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            process.Start();
            process.Close();
            // 删除临时文件
            //File.Delete(tempFilePath);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp";
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 检查图像大小
                FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                long fileSize = fileInfo.Length;

                if (fileSize > 1024 * 1024) // 1MB = 1024 * 1024 bytes
                {
                    MessageBox.Show("图片大小不能超过1MB");
                    return;
                }
                Image image = Image.FromFile(openFileDialog.FileName);
                InvoicesImage.Image = image;
                var str = image.ImageToBase64();
                InvoicesImage.Tag = str;
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (dataGridViewBuyDetail.SelectedCells.Count > 0)
            {
                foreach (DataGridViewCell cell in dataGridViewBuyDetail.SelectedCells)
                {
                    dataGridViewBuyDetail.Rows.RemoveAt(cell.RowIndex);
                }
            }
        }

        private void dataGridViewBuyDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridViewBuyDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

        }

        private void dataGridViewBuyDetail_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {

            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void InvoicesImage_Click(object sender, EventArgs e)
        {

        }

        private void dataGridViewBuyDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "GoodsName" && string.IsNullOrEmpty(dataGridViewBuyDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString()))
                {
                    MessageBox.Show("请选择商品");
                    dataGridViewBuyDetail.CurrentCell = dataGridViewBuyDetail.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    return;
                }
                if (dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "GoodsName")
                {

                    dataGridViewBuyDetail.Rows[e.RowIndex].Cells["GoodsCode"].Value = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["GoodsName"].Value;
                    var code = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["GoodsName"].Value.ToString();
                    var goods = _w_GoodsServices.QueryByClause(p =>
                        p.GoodsCode == code);
                    if (goods != null)
                    {
                        dataGridViewBuyDetail.Rows[e.RowIndex].Cells["GoodsUnit"].Value = goods.GoodsUnit;
                        dataGridViewBuyDetail.Rows[e.RowIndex].Cells["GoodsSpec"].Value = goods.GoodsSpec;
                    }
                }
                //数量
                if (dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "BuyNumber" || dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "UnitPrice" || dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "DiscountPrice" || dataGridViewBuyDetail.Columns[e.ColumnIndex].Name == "TaxRate")
                {
                    decimal value = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["BuyNumber"].Value == null ? 0 : dataGridViewBuyDetail.Rows[e.RowIndex].Cells["BuyNumber"].Value.ToDecimal();
                    //购货单价
                    decimal unitPrice = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["UnitPrice"].Value == null ? 0 : dataGridViewBuyDetail.Rows[e.RowIndex].Cells["UnitPrice"].Value.ToDecimal();
                    //折扣金额
                    decimal discountPrice = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["DiscountPrice"].Value == null ? 0 : dataGridViewBuyDetail.Rows[e.RowIndex].Cells["DiscountPrice"].Value.ToDecimal();
                    //税率
                    decimal taxRate = dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TaxRate"].Value == null
                        ? 0
                        : dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TaxRate"].Value.ToDecimal() / 100;

                    decimal jine = value * unitPrice - discountPrice;
                    //金额
                    dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TotalPriceD"].Value = jine;

                    decimal danjia = unitPrice * (1 + taxRate);

                    //含税单价
                    dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TaxUnitPrice"].Value = danjia;

                    //税额
                    decimal shuie = unitPrice * (taxRate) * value - discountPrice * taxRate;
                    dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TaxPrice"].Value = shuie;

                    //含税金额
                    dataGridViewBuyDetail.Rows[e.RowIndex].Cells["TotalTaxPrice"].Value =
                        shuie + jine;
                    SetFormTotalData();
                }
            }
        }

        private void SetFormTotalData()
        {
            decimal total = 0;
            foreach (DataGridViewRow row in dataGridViewBuyDetail.Rows)
            {
                if (!row.IsNewRow)
                {
                    total += row.Cells["TotalTaxPrice"].Value.ToDecimal();
                }
            }
            TotalPayable.Text = total.ToString();
        }

        private void tabPageGouhuo_Click(object sender, EventArgs e)
        {

        }

        private void TotalPayable_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl2.SelectedTab = tabPageGouhuo;
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns></returns>
        private bool CheckData(string code)
        {
            //是否有退货
            if (_w_BuyReturnServices.Exists(p => p.BuyCode == code))
            {
                MessageBox.Show("该采购单有退货记录，不能操作！", "提示");
                return false;
            }

            //是否是入库单
            if (_w_BuyInWarehouseServices.Exists(p => p.BuyCode == code))
            {
                MessageBox.Show("该采购单已入库，不能操作！", "提示");
                return false;
            }

            //是否已收款
            if (_w_PaymentDetailServices.Exists(p => p.BuyCode == code))
            {
                MessageBox.Show("该采购单已付款，不能操作！", "提示");
                return false;
            }
            return true;
        }
    }
}
